package jvDeformation.gui;

import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

public class RadioBox<E> extends Panel implements ItemListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1645691038878125794L;
	public final static int HORIZONTAL = 1;
	public final static int VERTICAL = 2;
	private CheckboxGroup checkboxGroup = new CheckboxGroup();
	private Hashtable<Checkbox, E> checkboxMap = new Hashtable<Checkbox, E>();
	private Hashtable<E, Checkbox> inverseCheckboxMap = new Hashtable<E, Checkbox>();
	public RadioBox(E[] data, int orientation) {
		super(generateLayout(orientation));
		boolean status = true;
		for (E e : data) {
			Checkbox c = new Checkbox(e.toString(), checkboxGroup, status);
			checkboxMap.put(c, e);
			inverseCheckboxMap.put(e, c);
			this.add(c);
			c.addItemListener(this);
			status = false;
		}
	}
	
	public void setEnabled(boolean b){
		for (Checkbox c : checkboxMap.keySet()) {
			c.setEnabled(b);
		}
	}
	
	
	
	public void setSelected(E o){
		if (inverseCheckboxMap.containsKey(o)) {
			checkboxGroup.setSelectedCheckbox(inverseCheckboxMap.get(o));
		}
	}
	
	public E getSelected(){
		return checkboxMap.get(checkboxGroup.getSelectedCheckbox());
	}
	
	static private GridLayout generateLayout(int id){
		switch (id) {
		case HORIZONTAL:
			return new GridLayout(1,0);
		case VERTICAL:
			return new GridLayout(0,1);
		default:
			return new GridLayout();
		}
	}
	
	
	private List<ActionListener> actionListeners = new ArrayList<ActionListener>();
	public boolean addActionListener(ActionListener listener){
		return actionListeners.add(listener);
	}
	
	public boolean removeActionListener(Object listener){
		return actionListeners.remove(listener);
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if (e.getStateChange() == ItemEvent.SELECTED) {
			ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, e.getItem().toString());
			for (ActionListener listener : actionListeners) {
				listener.actionPerformed(ae);
			}
		}
		
	}
	

	
	



}
